import common from './common.js'
import JSEncrypt from './rsa.js'

export default {
	baseUrl: 'http://' + common.remoteServer,
	//显示信息
	showMsg(data) {
		if (!data.Success) {
			common.showToast(data.ErrorMessage);
			return true;
		}
		return false;
	},
	//上传
	upload(data, defaultHandle) {
		if (undefined === defaultHandle || null === defaultHandle) {
			defaultHandle = true;
		}
		return new Promise((res, rej) => {
			const uploader = plus.uploader.createUpload(this.baseUrl + data.url, {
				method: 'POST',
				timeout: 10,
				retryInterval: 10
			}, (result, status) => {
				switch (status) {
					case 200:
						let data = result.responseText;
						if (typeof data === 'string') {
							data = JSON.parse(data);
						}
						if (!defaultHandle) {
							res(data);
							return;
						}
						if (this.showMsg(data)) {
							rej({
								handle: true,
								data
							});
							return;
						}
						res(data);
						break;
					case 401:
						common.showToast('无权限，请退出后重新登录');
						rej({
							handle: true
						});
						break;
					default:
						console.log(result, status);
						common.showToast('上传失败，请检查网路是否畅通');
						rej({
							handle: true
						});
						break;
				}
			});
			if (data.callback) {
				uploader.addListener('statechanged', data.callback);
			}
			uploader.setRequestHeader('Authorization', common.token);
			uploader.addFile(data.filePath, {
				key: 'key'
			});
			uploader.start();
		});
	},
	//下载
	download(url, fileName, callback) {
		return new Promise((res, rej) => {
			const downloader = plus.downloader.createDownload(this.baseUrl + url, {
				filename: fileName,
				timeout: 10,
				retryInterval: 10
			}, (result, status) => {
				switch (status) {
					case 200:
						res(result.filename);
						break;
					case 401:
						common.showToast('登录失效，请退出后重新登录');
						rej({
							handle: true
						});
						break;
					default:
						// common.showToast('下载失败，请检查网络是否畅通');
						rej({
							handle: true
						});
						break;
				}
			});
			if (callback) {
				downloader.addEventListener("statechanged", callback);
			}
			downloader.setRequestHeader('Authorization', common.token);
			downloader.start();
		});
	},
	//请求
	request(data, defaultHandle = true) {
		data.url = this.baseUrl + data.url;
		data.header = data.header || {
			Authorization: common.token
		};
		data.timeout = 60000;
		return new Promise((res, rej) => {
			data.success = respose => {
				switch (respose.statusCode) {
					case 200:
						if (respose.header.ReToken) {
							common.token = respose.header.ReToken;
						}
						if (!defaultHandle) {
							res(respose.data);
							return;
						}
						if (this.showMsg(respose.data)) {
							rej({
								handle: true,
								data: respose.data
							});
							return;
						}
						res(respose.data);
						break;
					case 401:
						common.showToast('无权限，请退出后重新登录');
						rej({
							handle: true
						});
						break;
					default:
						common.showToast('请求失败，请检查网路是否畅通');
						rej({
							handle: true
						});
						break;
				}
			};
			data.fail = async err => {
				let [result, type] = await uni.getNetworkType();
				if (type.networkType == 'none') {
					common.showToast('网络不可用');
					rej({
						handle: true
					});
					return;
				}
				rej(err);
			};
			uni.request(data);
		});
	},
	//登录
	login(data) {
		const encrypt = new JSEncrypt();
		encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----' + common.publicKey + '-----END PUBLIC KEY-----');
		data.Password = encrypt.encrypt(data.Password);
		return this.request({
			url: '/Server/Login',
			method: 'POST',
			data
		});
	},
	//注册
	register(data) {
		return this.request({
			url: '/Server/Register',
			method: 'POST',
			data
		});
	},
	//获取服务器时间
	getServerTime() {
		return this.request({
			url: '/Server/GetSystemTime'
		}, false);
	},
	//获取RSA公钥
	getRSAPublicKey() {
		return this.request({
			url: '/Server/GetRSAPublicKey'
		}, false);
	},
	//获取群组
	getGroups() {
		return this.request({
			url: '/Server/GetGroups'
		});
	},
	//获取好友
	getFriends() {
		return this.request({
			url: '/Server/GetFriends'
		});
	},
	//获取所有申请
	getApplies(data) {
		return this.request({
			url: '/Server/GetApplyMessages',
			data
		});
	},
	//删除好友
	deleteFriend(data) {
		return this.request({
			url: '/Server/DeleteFriend',
			data
		});
	},
	//更换头像
	changeAvatar(data) {
		return this.upload({
			filePath: data,
			url: '/Server/ChangeAvatar'
		});
	},
	//下载头像
	downloadAvatar(data) {
		return this.download('/Server/DownloadAvatar?fileName=' + data, common.avatarFolder);
	},
	//下载文件
	downloadFile(data, callback) {
		return this.download('/Server/DownloadFile?code=' + data, common.chatFolder, callback);
	},
	//上传文件
	uploadFile(data) {
		return this.upload({
			filePath: data.filePath,
			url: `/Server/ImportFile?receiverId=${data.receiverId}&type=${data.type}`
		});
	},
	//检查版本
	checkVersion(data) {
		return this.request({
			url: '/Server/CheckVersion',
			data
		}, false);
	},
	//获取未处理请求总数
	getUnhandledAppliesCount() {
		return this.request({
			url: '/Server/GetUnhandledApplies'
		});
	},
	//搜索好友
	searchFriends(data) {
		return this.request({
			url: '/Server/SearchFriends?keyWords=' + data,
		}, false);
	},
	//获取登录验证码
	getLoginCaptcha(data) {
		return this.request({
			url: '/Server/GetLoginCaptcha',
			method: 'POST',
			data
		});
	},
	//根据邮箱手机登录
	loginByEmailPhone(data) {
		return this.request({
			url: '/Server/LoginByEmailPhone',
			method: 'POST',
			data
		});
	},
	//检查并下载头像
	async checkDownloadAvatar(data) {
		let exists = await common.checkAvatar(data);
		//头像不存在则下载
		if (!exists) {
			await this.downloadAvatar(data);
		}
	},
	//批量检查并下载头像
	async BatchCheckDownloadAvatars(data) {
		if (!Array.isArray(data)) {
			return Promise.resolve();
		}
		data = Array.from(new Set(data));
		return Promise.all(
			data.map(
				avatar =>
				new Promise(async (res, rej) => {
					try {
						await this.checkDownloadAvatar(avatar);
					} catch (e) {
						console.log(avatar, '下载失败', e);
					}
					res();
				})
			)
		);
	}
}
